
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import pandas as pd
from  utils import column_letter_to_index
import re
'''

我现在需要处理很多条这样的数据，每一条数据是dataframe类型数据的一行，它显示是否患病 可能有一下几种形式：
1 "无慢性病"
2 患了某种慢性病，以及年限，例如：患慢性消化系统疾病（年限）〖9〗┋患颈椎或腰椎疾病（年限）〖11〗不同的病之间用┋隔离，患病年限用〖〗包围的数字表示，
输出要求：
1.首先统计一共出现了N种病症，那么输出就有N列，有M行数据，所以最终结果是MxN
2.如果某个患者得了这种病，那么该行对应的这一列应当填1，否则填上0，
给我python代码
'''
# 使用刚才定义的函数extract_diseases来提取每个病症及其年限
# 这次我们需要保留患病年限信息
def extract_diseases_with_duration(record):
    if record == "无慢性病":
        return {}
    diseases = re.split('┋', record)
    disease_dict = {}
    for disease in diseases:
        name = re.search('(.*?)（年限）', disease).group(1)
        duration = re.search('〖(.*?)〗', disease).group(1)
        disease_dict[name] = int(duration)
    return disease_dict

data_path = '../../data/raw_data/慢性病患病及年限 334份.xlsx'
df = pd.read_excel(data_path)
index = column_letter_to_index('K')
df_select = df.iloc[:, index]
print(df_select.head())



# Assuming 'data' is a list of strings representing the health records
# Replace this with your actual dataframe column
data = df_select # Your dataframe column here



# 再次处理数据
disease_data_with_duration = data.apply(extract_diseases_with_duration)

all_diseases = set()
for record in disease_data_with_duration:
    all_diseases.update(record.keys())

# 为每位患者创建一个字典，键为疾病名称，值为患病年限，如果未患病则为0
disease_matrix_with_duration = []
for record in disease_data_with_duration:
    patient_diseases = {disease: 0 for disease in all_diseases}  # 先初始化所有病症的值为0
    patient_diseases.update(record)  # 更新字典，患病的病症将其年限填入
    disease_matrix_with_duration.append(patient_diseases)

# 将疾病矩阵转换为 DataFrame
disease_df_with_duration = pd.DataFrame(disease_matrix_with_duration)

# 显示结果
print(disease_df_with_duration.info())

output_filename = '../../output/dealed_data/disease_df_with_duration.xlsx'
disease_df_with_duration.to_excel(output_filename, index=False)
    # df_encoded.to_excel'/'+output_filename, index=False)